//拦截器
import axios from 'axios'
import VUE_APP_BASE_API from '@/api/http.js'
import VUE_APP_BASE_API_5G from '@/api/http5g.js'
function startLoading() {
    uni.showLoading({
        lock: true,
        text: '加载中……',
        background: 'rgba(255, 255, 255, 0.9)'
    })
}
function endLoading() {
    uni.hideLoading()
}
const STATUS_CODE_MAP = new Map([
    [400,'错误请求'],
    [401,'未授权 请重新登录'],
    [403,'拒绝访问'],
    [404,'请求错误，没找到资源'],
    [405,'请求方法未允许'],
    [408,'请求超时'],
    [500,'服务器端出错'],
    [501,'网络未实现'],
    [502,'网络错误'],
    [503,'错误请求'],
    [504,'网络超时'],
    [505,'http版本不支持请求']
])


class HttxError extends Error {
	constructor(message) {
		super(message);
		this.name = this.constructor.name;
	}
}
class HttxStatusError extends HttxError {
	constructor(message, statusCode, dataResult) {
		super(message);
		this.name = this.constructor.name;
		this.statusCode = statusCode;
		this.dataResult = dataResult;
	}
}


//创建实例
const service = axios.create({
    timeout: 30*1000
})

//请求拦截器
service.interceptors.request.use(config=>{
    startLoading()
    config.headers = config.headers || {
        'content-type': 'application/x-www-form-urlencoded',
    }
    //token
    var token = uni.getStorageSync("token")||'';
    if(token){
        config.headers['token'] = '' + token;
        config.headers['domain'] = '' + VUE_APP_BASE_API.VUE_APP_BASE_API
    }
    return config
},error=>{
    Promise.reject(error)
})

// 响应拦截白名单，白名单中的url不做拦截（调用者自行处理接口反馈的各种异常情况）
const WHITE_LIST=[
	'/api/card_code/activation'
]
//响应拦截
service.interceptors.response.use(response => {
    endLoading()
	//白名单过滤
	let flag = false 
	WHITE_LIST.forEach(u=>{
		flag = response.config.url.endsWith(u)
	})
	if(response.data.code != 1 && !flag){
		uni.showModal({
			title: '',
			showCancel: false,
			content: response.data.msg,
		});
		return Promise.reject(new Error(response.data.msg || 'Error'))
	}else {
		return response
	}
}, error => {
	console.log(error)
    endLoading()
    let statusCode = error.response.status;
    let dataResult = error.response.data;

    try {
        if (statusCode >= 500) {// 5xx
            throw new HttxStatusError('系统错误', statusCode, dataResult);
        } else if (statusCode >= 400) {// 4xx
            throw new HttxStatusError('请求出错', statusCode, dataResult);
        }
        throw new Error(`Unsupported statusCode ${statusCode}`);
    } catch (error2) {
        //return error2
        handleError(error2);
    }
})

function handleError(error) {
	if (error instanceof HttxStatusError) {
		let statusCode = error.statusCode;
		let dataResult = error.dataResult;
		console.log(statusCode)
		if (statusCode == 401) {
			uni.removeStorageSync('token')
			//请先登录
			uni.reLaunch({
				url:'/pages/login/login'
			})
			// uni.showModal({
			// 	title: '登录失效',
			// 	content: '即将跳转到登录页面',
			// 	showCancel:false,
			// 	success: function (res) {
			// 		//请先登录
			// 		uni.reLaunch({
			// 			url:'/pages/login/login'
			// 		})
			// 	}
			// });
		} else {
			let msg;
			if (Object.prototype.toString.call(dataResult) === '[object Object]') {
				msg = dataResult.msg;
			}
			msg = msg || STATUS_CODE_MAP.get(statusCode) || error.message;
			uni.showModal({content:msg,showCancel: false})
			console.log(msg);
		}
	} else if (error instanceof Error) {
		uni.showModal({content:error.message,showCancel: false})
		console.log(error.message);
	} else {
		uni.showModal({content:error,showCancel: false})
		console.log(error);
	}

	throw error;
}
//真机获取  
 axios.defaults.adapter = function (config) {  
     return new Promise((resolve, reject) => {  
         var settle = require('axios/lib/core/settle');  
         var buildURL = require('axios/lib/helpers/buildURL');  
         uni.request({  
             method: config.method.toUpperCase(),  
             url: buildURL(config.url, config.params, config.paramsSerializer),  
             header: config.headers,  
             data: config.data,  
             dataType: config.dataType,  
             responseType: config.responseType,  
             sslVerify: config.sslVerify,  
             complete:function complete(response){  
                 response = {  
                   data: response.data,  
                   status: response.statusCode,  
                   errMsg: response.errMsg,  
                   header: response.header,  
                   config: config  
                 };  
 
             settle(resolve, reject, response);  
             }  
         })  
     })  
 }

export default service
